package com.shaoyu.spring.study;

import com.shaoyu.spring.study.runner.ConcurrentWarp;
import com.shaoyu.spring.study.runner.HandlerRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author : Swicky
 * @date : 2021/4/20 - 3:11 下午
 */
public class HandlerConfig {

    @Bean
    @ConditionalOnMissingBean(ExecutorService.class)
    public ExecutorService parallelExecutorService(){
        int cpu = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(cpu * 2,
                cpu * 8,
                5,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000));
        return threadPoolExecutor;
    }

    @Bean
    @ConditionalOnMissingBean(ConcurrentWarp.class)
    public ConcurrentWarp callableWarp(){
        ConcurrentWarp concurrentWarp = new ConcurrentWarp() {
            @Override
            public <V> Callable<V> warp(Callable<V> callable) {
                return callable;
            }

            @Override
            public Runnable warp(Runnable runnable) {
                return runnable;
            }
        };
        return concurrentWarp;
    }

    @Bean
    public HandlerRunner handlerRunner(ExecutorService executorService, ConcurrentWarp concurrentWarp){
        return new HandlerRunner(concurrentWarp,executorService);
    }

}
